package com.fin.zw.intelligentbot.controller;

import com.fin.zw.intelligentbot.annotation.CurrentUser;
import com.fin.zw.intelligentbot.entity.QWebSocketMessage;
import com.fin.zw.intelligentbot.entity.WebSocketMessage;
import com.fin.zw.intelligentbot.enums.MessageMode;
import com.fin.zw.intelligentbot.enums.MessageReadStatus;
import com.fin.zw.intelligentbot.model.request.MsgRequest;
import com.fin.zw.intelligentbot.model.request.WebSocketMessageModel;
import com.fin.zw.intelligentbot.model.response.WebSocketMessageResponse;
import com.fin.zw.intelligentbot.model.session.SessionModel;
import com.fin.zw.intelligentbot.repository.WebSocketMessageRepository;
import com.fin.zw.intelligentbot.service.WebSocketService;
import com.querydsl.core.BooleanBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;

@RestController
@RequestMapping("/webSocketMsg")
@Api(value = "消息服务", description = "消息服务")
public class WebSocketMsgController {

    Logger logger = LoggerFactory.getLogger(WebSocketMsgController.class);


    @Autowired
    WebSocketService webSocketService;

    @Autowired
    WebSocketMessageRepository webSocketMessageRepository;

    @PostMapping("/sendMsgByUserId")
    @ApiOperation(value = "发送消息", notes = "发送消息")
    public ResponseEntity sendMsgByUserId(@RequestBody WebSocketMessageModel message, @RequestParam("userName") String userName) {
        webSocketService.sendMessage(userName, message);
        return ResponseEntity.ok(null);
    }

    @GetMapping("/fetchPage")
    @ApiOperation(value = "查询消息列表", notes = "查询消息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query",
                    value = "页数 (0..N)"),
            @ApiImplicitParam(name = "size", dataType = "integer", paramType = "query",
                    value = "每页大小."),
            @ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query",
                    value = "依据什么排序: 属性名(,asc|desc). ")
    })
    public ResponseEntity<Page<WebSocketMessageResponse>> getMsgList(Pageable pageable,
                                                                     @RequestParam(value = "messageReadStatus", required = false) MessageReadStatus messageReadStatus,
                                                                     @ApiIgnore @CurrentUser SessionModel sessionModel) throws Exception {

        BooleanBuilder booleanBuilder = new BooleanBuilder();
        QWebSocketMessage qWebSocketMessage = QWebSocketMessage.webSocketMessage;
        booleanBuilder.and(qWebSocketMessage.userName.eq(sessionModel.getUserName()));
        if (Objects.nonNull(messageReadStatus)) {
            booleanBuilder.and(qWebSocketMessage.readStatus.eq(messageReadStatus));
        }
        //Sort sort =new Sort(Sort.Direction.DESC, "webSocketMessageModel.msgDate");
        Page<WebSocketMessageResponse> allList = webSocketMessageRepository.findAll(booleanBuilder, pageable).map(webSocketMessage -> {
            WebSocketMessageResponse response = new WebSocketMessageResponse();
            BeanUtils.copyProperties(webSocketMessage, response);
            return response;
        });
        return ResponseEntity.ok().body(allList);
    }

    @GetMapping("/getUnReadMsgCount")
    @ApiOperation(value = "获取未读消息总数", notes = "获取未读消息总数")
    public ResponseEntity<Long> getUnReadMsgCount(@CurrentUser SessionModel sessionModel) throws Exception {

        BooleanBuilder booleanBuilder = new BooleanBuilder();
        QWebSocketMessage qWebSocketMessage = QWebSocketMessage.webSocketMessage;
        booleanBuilder.and(qWebSocketMessage.userName.eq(sessionModel.getUserName()));
        booleanBuilder.and(qWebSocketMessage.readStatus.eq(MessageReadStatus.UNREAD));
        Long reponse = webSocketMessageRepository.count(booleanBuilder);
        return ResponseEntity.ok().body(reponse);
    }

    @PostMapping("/updateMsgStatus")
    @ApiOperation(value = "更新消息状态", notes = "更新消息状态")
    public ResponseEntity updateMsgStatus(@RequestBody MsgRequest updateMsgRequest) throws Exception {
        if (Objects.nonNull(updateMsgRequest)) {
            if (updateMsgRequest.getIds() != null) {
                BooleanBuilder booleanBuilder = new BooleanBuilder();
                QWebSocketMessage qWebSocketMessage = QWebSocketMessage.webSocketMessage;
                booleanBuilder.and(qWebSocketMessage.id.in(updateMsgRequest.getIds()));
                Iterator<WebSocketMessage> webSocketMessages = webSocketMessageRepository.findAll(booleanBuilder).iterator();
                List<WebSocketMessage> list = new ArrayList<>();
                while (webSocketMessages.hasNext()) {
                    WebSocketMessage webSocketMessage = webSocketMessages.next();
                    webSocketMessage.setReadStatus(MessageReadStatus.READ);
                    list.add(webSocketMessage);
                }
                webSocketMessageRepository.saveAll(list);
            }
        }
        return ResponseEntity.ok().body(null);
    }

    @PostMapping("/getMsgDetail")
    @ApiOperation(value = "获取消息详情", notes = "获取消息详情")
    public ResponseEntity<WebSocketMessageResponse> getMsgDetail(@RequestParam String id) throws Exception {
        Optional<WebSocketMessage> webSocketMessage = webSocketMessageRepository.findById(id);
        WebSocketMessageResponse response = new WebSocketMessageResponse();
        if (webSocketMessage.isPresent()) {
            BeanUtils.copyProperties(webSocketMessage, response);
        }
        return ResponseEntity.ok().body(response);
    }

    @GetMapping("/getWorkbenchReminder")
    @ApiOperation(value = "弹框消息", notes = "弹框消息")
    public ResponseEntity<Page<WebSocketMessageResponse>> getWorkbenchReminder(@CurrentUser SessionModel sessionModel) {

        BooleanBuilder booleanBuilder = new BooleanBuilder();
        QWebSocketMessage qWebSocketMessage = QWebSocketMessage.webSocketMessage;
        booleanBuilder.and(qWebSocketMessage.userName.eq(sessionModel.getUserName()));
        booleanBuilder.and(qWebSocketMessage.readStatus.eq(MessageReadStatus.UNREAD));
        booleanBuilder.and(qWebSocketMessage.messageMode.eq(MessageMode.POPUP));
        Sort sort = new Sort(Sort.Direction.DESC, "webSocketMessageModel.msgDate");
        Pageable pageable = PageRequest.of(0, 3, sort);

        Page<WebSocketMessageResponse> page = webSocketMessageRepository.findAll(booleanBuilder, pageable).map(webSocketMessage -> {
            WebSocketMessageResponse response = new WebSocketMessageResponse();
            BeanUtils.copyProperties(webSocketMessage, response);
            return response;
        });
        return ResponseEntity.ok().body(page);
    }

    @PostMapping("/deletedReminderMessage")
    @ApiOperation(value = "删除提醒消息", notes = "删除提醒消息")
    public ResponseEntity<Void> deletedReminderMessage(@RequestBody MsgRequest messageDeletedRequest) {
        logger.info("删除提醒消息开始" + messageDeletedRequest);
        Iterable<WebSocketMessage> allById = webSocketMessageRepository.findAllById(messageDeletedRequest.getIds());
        webSocketMessageRepository.deleteAll(allById);
        return ResponseEntity.ok(null);
    }

    @GetMapping("/testSendMsg")
    @ApiOperation(value = "消息测试", notes = "消息测试")
    public ResponseEntity testSendMsg() {
        WebSocketMessageModel message = new WebSocketMessageModel();
        message.setContent("这是一个测试消息");
        webSocketService.sendMessage("task", message);
        return ResponseEntity.ok().body(null);
    }

}
